#
# smsq - send and manage sms on a huawei 3g modem
# http://code.google.com/p/smsq/
#
# Pedro Cardoso (pcardoso@gmail.org)
# http://luminescente.com
# built on Mac OS X, should work on any other *nix
#

# NOTES
# overlay gauge on top of statusbar: http://lists.wxwidgets.org/pipermail/wxpython-users/2003-October/023241.html

import wx
from smsq import Modem
import wx.lib.dialogs

class MyNotebook(wx.Frame):
	def __init__(self, parent, title):
		wx.Frame.__init__(self, parent, wx.ID_ANY, title, size=(520, 400))

		# style=wx.NB_TOP is default
		# could use style=wx.NB_BOTTOM
		# self.AddSpacer((8, 8))				
		self.nb = wx.Notebook(self, wx.ID_ANY)
		# MyPage(parent, conversion dictionary, preselected choice)
				
		# list tab 
		self.list_page = wx.Panel(self.nb);
		self.list = wx.ListView(self.list_page, pos=(0,0), size=(500,300),style = wx.LC_REPORT | wx.LC_SINGLE_SEL 
                                 # | wx.BORDER_NONE
								# | wx.LC_LIST
								| wx.LC_EDIT_LABELS
								| wx.LC_SORT_ASCENDING)
		# self.list.Create(self.list_page, parent, id=-1, pos=DefaultPosition, size=DefaultSize, style=LC_ICON, validator=DefaultValidator, name=ListCtrlNameStr)
		self.list.InsertColumn(1, "ID")
		self.list.InsertColumn(2, "Sender")
		self.list.InsertColumn(3, "Status")				
		self.list.InsertColumn(4, "Date")				
		self.list.InsertColumn(5, "Text")
		self.list.SetColumnWidth(0, 20)		
		self.list.SetColumnWidth(2, 140)		
		self.list.SetColumnWidth(4, 180)
		self.list.Bind(wx.EVT_LIST_ITEM_SELECTED, self.onSelectSMS)
		self.list.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.onReply)		
		self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.onDeselectSMS)
		
		
		self.text = wx.TextCtrl(self.list_page, wx.ID_ANY, value="", size=(320, 100),style=wx.TE_MULTILINE | wx.TE_READONLY)
		self.text.Disable();
		
		self.delete_button = wx.Button(self.list_page, wx.ID_ANY, label='Delete')
		self.delete_button.Bind(wx.EVT_BUTTON, self.onDelete)
		self.delete_button.Disable();
		
		sizer_list = wx.BoxSizer(wx.VERTICAL)
		
		sizer_list.Add(self.list, 1, wx.ALIGN_LEFT | wx.EXPAND | wx.ALL, 5) # wx.EXPAND
		sizer_list.Add(self.text, 0, wx.ALL | wx.EXPAND, 5)				
		sizer_list.Add(self.delete_button, 0, wx.ALIGN_RIGHT  | wx.ALL, 5)				
		self.list_page.SetSizer(sizer_list)

		# list tab
		self.send_page = wx.Panel(self.nb);		
		self.to_label = wx.StaticText(self.send_page, wx.ID_ANY, "To:")
		self.to_text = wx.TextCtrl(self.send_page, wx.ID_ANY, value="", size=(150, 20))
		self.message_label = wx.StaticText(self.send_page, wx.ID_ANY, "Text:")		
		self.message_text = wx.TextCtrl(self.send_page, wx.ID_ANY, value="", size=(320, 100),style=wx.TE_MULTILINE)
		self.smsc_label = wx.StaticText(self.send_page, wx.ID_ANY, "SMS center:")
		self.smsc_text = wx.TextCtrl(self.send_page, wx.ID_ANY, value="", size=(150, 20))
		
		self.button = wx.Button(self.send_page, wx.ID_ANY, label='Send')
		self.button.Bind(wx.EVT_BUTTON, self.onSend)
		
		sizer_send = wx.FlexGridSizer(4, 2, 10, 10)
		# sizer_send = wx.BoxSizer(wx.VERTICAL)

		sizer_send.Add(self.to_label, wx.ALL, 5)
		sizer_send.Add(self.to_text, wx.ALL, 5)
		sizer_send.Add(self.message_label, wx.ALL, 5)
		sizer_send.Add(self.message_text, wx.ALL, 5)
		sizer_send.Add(self.smsc_label, wx.ALL, 5)
		sizer_send.Add(self.smsc_text, wx.ALL, 5)		
		sizer_send.AddSpacer(1)						
		sizer_send.Add(self.button)		
		self.send_page.SetSizer(sizer_send)
		
		# self.send_page = MyPage(nb, areaD, 2)
		self.nb.AddPage(self.list_page, "SMS List")
		self.nb.AddPage(self.send_page, "Send")
		# start with page1 active
		self.list_page.SetFocus()
		# self.send.SetFocus()
		
		self.statusbar = self.CreateStatusBar()
		self.statusbar.SetFieldsCount(2)

		# self.statusbar.SetStatusText("Loaded...")
		
		self.get_modem()
		self.update_sms()
		self.update_status()

		
   		self.timer = wx.Timer(self)
		self.Bind(wx.EVT_TIMER, self.tick, self.timer)
		self.timer.Start(10 * 1000)
		
	def update_sms(self):
		sms = self.modem.sms_list()
		# self.list.DeleteAllItems()				
		# self.grid.AppendRows(len(sms))
		for m in sms:
			id, status, sender, date, text = m

			# search in existing
			e = False
			item = self.list.GetNextItem(-1)
			while item != -1:
				if self.list.GetItem(item, 0).GetText() == id:
					e = True
				item = self.list.GetNextItem(item, wx.LIST_NEXT_BELOW)		
				     
			
			if not e:
				self.list.Append((id, status, sender, date, text.strip()))
				          
	def update_status(self):		
		"""Update network info on the statusbar"""
		self.statusbar.SetStatusText(
			"Network: %s" % self.modem.get_network(), 0)
		# TODO:	translate this to something sensible	
		self.statusbar.SetStatusText(
		"Signal strength: %s " %
			self.modem.get_signal_strength(), 1)
			
		
  		                                                                                                   
	def onSend(self, event):
		to = str(self.to_text.GetValue())
		msg = str(self.message_text.GetValue())
		smsc = str(self.smsc_text.GetValue())
		if to and msg and smsc:
			self.modem.set_smsc(smsc)
			self.modem.send_sms(to, msg)
			self.alert("Message sent")
			self.to_text.SetValue("")
			self.message_text.SetValue("")
			self.nb.SetSelection(0)
		else:
			self.alert("Oops! Something is missing...")
			
	def onDelete(self, event):		
		if self.modem.sms_delete(int(self.currentItem)):
			self.list.DeleteItem(int(self.currentItem))
		
	def onSelectSMS(self, event):
		i = event.m_itemIndex
		self.currentItem = self.list.GetItem(i, 0).GetText()		
		self.text.SetValue(self.list.GetItem(i, 4).GetText())
		
		self.text.Enable()		
		self.delete_button.Enable()		
		
	def onDeselectSMS(self, event):
		self.text.SetValue("")
		self.text.Disable()		
		self.delete_button.Disable()
		
	def onReply(self, event):
		i = event.m_itemIndex		
		self.to_text.SetValue(self.list.GetItem(i, 2).GetText())
		self.nb.SetSelection(1)
		
	def tick(self, event):
		self.update_sms()
		self.update_status()
		
		
	def alert(self, msg):
		wx.lib.dialogs.messageDialog(self, msg, 'smsq', wx.OK)
		
	def die(self, msg):
		wx.lib.dialogs.messageDialog(self, msg, 'Error', wx.OK)
		sys.exit(-1)

	def get_modem(self):
		com_port = "/dev/cu.HUAWEIMobile-Pcui"
		self.modem = Modem(com_port)
		if not self.modem.modem_exists:
			self.die('No modem detected.')
		if self.modem.requested_pin():
			pin = self.get_pin()
			if pin:
				self.modem.set_pin(pin)
			else:
				self.die('No PIN given')
		self.modem.set_textmode()

	def get_pin(self):
		result = wx.lib.dialogs.textEntryDialog ( self, 'Enter your PIN', 'PIN?', '')
		if result.accepted:
			return result.text
		else:
			self.die('No PIN was entered')
		

if __name__ == '__main__':
	app = wx.App(0)
	mynotebook = MyNotebook(None, "smsq")
	mynotebook.Show()
	app.MainLoop()